#!/usr/bin/env python
import twitter
import emotion
import sampler

from Queue import Queue, Empty
import sys

from os.path import dirname, abspath
from os import chdir
chdir(dirname(abspath(__file__)))


class Encode():
	def __init__(self, stdout, enc):
		self.stdout = stdout
		self.encoding = enc
	def write(self, s):
		self.stdout.write(s.encode(self.encoding))
sys.stdout = Encode(sys.stdout, 'utf-8')


if __name__ == "__main__":
	emo = emotion.Emotion('emotion.db')
	sampler = sampler.Sampler('sampler.db')
	userque = Queue()
	publicque = Queue()
	userstream = twitter.userstream(userque)
	publicstream = twitter.publicstream(publicque)

	while True:
		try:
			for i in xrange(publicque.qsize()):
				data = publicque.get(timeout=5)
				try:
					sampler.parse_text(data)
					publicque.task_done()
				except Exception, e:
					print "public data parse error"
					e.print_stack()


				data = userque.get(timeout=10) #set timeout to be interruptable
				if data:
					if data['type'] == 'status':
						emo.parse_text(data['userid'], data['text'])
					elif data['type'] == 'mention':
						emo.parse_text(data['userid'], data['text'], weight=1.3)
					elif data['type'] == 'following' or data['type'] == 'followed':
						emo.add_person(data['userid'])

					"""add to sampler"""
					if data['type'] in ('status', 'mention'):
						publicque.put(data['text'])

					userque.task_done()

					emotion = emo.get_emotion()
					state = emo.get_state()
					for key in emotion.keys():
						print "%8s: %.5f [%s]"%(key, emotion[key], state[key])
		except Empty:
			pass
		except KeyboardInterrupt:
			print "Exit..."
			userstream.running = False
			publicstream.running = False
			sys.exit(0)
